package com.haiyi.software.app;

import org.jivesoftware.smack.packet.Message;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.haiyi.software.app.basic.ActivityEx;
import com.haiyi.software.entity.BeanLoginArgs;
import com.haiyi.software.entity.UserInfo;
import com.haiyi.software.tools.MyDBHelper;
import com.haiyi.software.tools.MyTools;

public class LoginActivity extends ActivityEx implements OnClickListener {

	private static final String TAG = "LoginActivity";

	private Button loginButton;

	private EditText loginNameText;

	private EditText loginPassText;

	private SharedPreferences sp;

	private Button registerButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		MainApplication.getInstance().setMineUserInfo(null);

		sp = this.getSharedPreferences("WHOESYOU", Context.MODE_PRIVATE);

		setContentView(R.layout.activity_login);

		initComp();

		autoLogin();
	}

	private void autoLogin() {
		// TODO 自动生成的方法存根
		String u = sp.getString("USER_NAME", "");
		String p = sp.getString("PASSWORD", "");
		if (u.length() > 0 && p.length() > 0) {

			loginNameText.setText(u);
			loginPassText.setText(p);

			loginIn(u, p);
		} else {

		}
	}

	private void playAnimate() {

		Display display = getWindowManager().getDefaultDisplay();

		TranslateAnimation tAnimation = new TranslateAnimation(0, 0, 0,
				-display.getHeight());
		tAnimation.setDuration(1000);

		tAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO 自动生成的方法存根

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO 自动生成的方法存根

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO 自动生成的方法存根

			}
		});

	}

	private void initComp() {

		// TODO 自动生成的方法存根
		loginButton = (Button) this.findViewById(R.id.btn_login);
		loginNameText = (EditText) this.findViewById(R.id.login_name);
		loginPassText = (EditText) this.findViewById(R.id.login_pass);
		this.registerButton = (Button) this.findViewById(R.id.btn_launchReg);

		loginButton.setOnClickListener(this);
		this.registerButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:

			if (loginNameText.getText().toString().trim().length() > 0
					&& loginPassText.getText().toString().trim().length() > 0) {

				loginIn(loginNameText.getText().toString().trim(),
						loginPassText.getText().toString().trim());
			} else {

				Toast.makeText(LoginActivity.this, "请输入登陆邮箱，密码",
						Toast.LENGTH_LONG).show();
			}

			break;
		case R.id.btn_launchReg:
			Intent intent = new Intent();
			intent.setClass(this, RegisterUsername.class);
			startActivity(intent);
			break;
		}
	}

	private void loginIn(String loginName, String loginPwd) {
		// TODO 自动生成的方法存根
		watingDialog.show();

		BeanLoginArgs loginBody = new BeanLoginArgs();

		loginBody.setLgname(loginName);
		loginBody.setPwd(loginPwd);
		loginBody.setClienttype("android");
		loginBody.setLgmode("前台");

		Location loc = new MyTools().getLocation();
		if (loc != null) {
			loginBody.setLat(loc.getLatitude());
			loginBody.setLongitude(loc.getLongitude());

			Log.i("loc", loc.getLatitude() + "" + loc.getLongitude());
		} else {
			loginBody.setLat(0);
			loginBody.setLongitude(0);
		}
		requestNetworkData(loginBody);

	}

	private long exitTime = 0;

	@Override
	public void requestFinish(JsonObject jsonObject_return) {

		watingDialog.cancel();

		JsonObject jsonObj_LoginReturn = null;

		try {
			jsonObj_LoginReturn = jsonEle_LoginReturn.getAsJsonObject();
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(this, "网络错误，登陆失败", Toast.LENGTH_LONG).show();
			return;
		}

		int state_LoginReturn = jsonObj_LoginReturn.get("state").getAsInt();

		switch (state_LoginReturn) {
		case 200:

			JsonObject jsonObj_returnBody = jsonObj_LoginReturn.get("body")
					.getAsJsonObject();

			// 登陆openfile
			if (app.getmXMPPStream().connection(
					jsonObj_returnBody.get("uid").getAsString(),
					jsonObj_returnBody.get("pwd").getAsString())) {

				// 默认保存当前帐号密码
				// 记住用户名、密码、
				Editor editor = sp.edit();
				editor.putString("USER_NAME", jsonObj_returnBody.get("uid")
						.getAsString());
				editor.putString("PASSWORD", jsonObj_returnBody.get("pwd")
						.getAsString());

				editor.commit();

				// 把登陆成功的内容保存
				UserInfo mine = MainApplication.getInstance().getMineUserInfo();

				mine.setApplestate(jsonObj_returnBody.get("applestate")
						.isJsonNull() ? 0 : jsonObj_returnBody
						.get("applestate").getAsInt());
				mine.setClienttype(jsonObj_returnBody.get("clienttype")
						.isJsonNull() ? "android" : jsonObj_returnBody.get(
						"clienttype").getAsString());
				mine.setEmail(jsonObj_returnBody.get("email").isJsonNull() ? ""
						: jsonObj_returnBody.get("email").getAsString());
				mine.setGold(jsonObj_returnBody.get("gold").isJsonNull() ? 0
						: jsonObj_returnBody.get("gold").getAsInt());
				mine.setLastdatetime(jsonObj_returnBody.get("lastdatetime")
						.isJsonNull() ? "" : jsonObj_returnBody.get(
						"lastdatetime").getAsString());
				mine.setLat(jsonObj_returnBody.get("lat").isJsonNull() ? 0
						: jsonObj_returnBody.get("lat").getAsDouble());
				mine.setLongitude(jsonObj_returnBody.get("longitude")
						.isJsonNull() ? 0 : jsonObj_returnBody.get("longitude")
						.getAsDouble());
				mine.setPhone(jsonObj_returnBody.get("phone").isJsonNull() ? ""
						: jsonObj_returnBody.get("phone").getAsString());
				mine.setPwd(jsonObj_returnBody.get("pwd").getAsString());
				mine.setRid(jsonObj_returnBody.get("rid").getAsString());
				mine.setSpcontent("");// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
				mine.setUbirthday(jsonObj_returnBody.get("ubirthday")
						.getAsString());
				mine.setUbody(jsonObj_returnBody.get("ubody").isJsonNull() ? ""
						: jsonObj_returnBody.get("ubody").getAsString());
				mine.setUedu(jsonObj_returnBody.get("uedu").isJsonNull() ? ""
						: jsonObj_returnBody.get("uedu").getAsString());
				mine.setUguid(jsonObj_returnBody.get("uguid").getAsString());
				mine.setHeadSmall(jsonObj_returnBody.get("headSmall")
						.getAsString());// 一个头像
				mine.setUheight(jsonObj_returnBody.get("uheight").isJsonNull() ? "0"
						: jsonObj_returnBody.get("uheight").getAsString());
				mine.setUid(jsonObj_returnBody.get("uid").getAsString());
				mine.setUmoney(jsonObj_returnBody.get("umoney").isJsonNull() ? ""
						: jsonObj_returnBody.get("umoney").getAsString());
				mine.setUname(jsonObj_returnBody.get("uname").getAsString());
				mine.setUsername(jsonObj_returnBody.get("username")
						.isJsonNull() ? "" : jsonObj_returnBody.get("username")
						.getAsString());

				mine.setUsex(jsonObj_returnBody.get("usex").isJsonNull() ? "1"
						: jsonObj_returnBody.get("usex").getAsString());
				mine.setUstar(jsonObj_returnBody.get("ustar").isJsonNull() ? ""
						: jsonObj_returnBody.get("ustar").getAsString());
				mine.setUwork(jsonObj_returnBody.get("uwork").isJsonNull() ? ""
						: jsonObj_returnBody.get("uwork").getAsString());
				mine.setVgold(jsonObj_returnBody.get("vgold").isJsonNull() ? 0
						: jsonObj_returnBody.get("vgold").getAsInt());
				mine.setZone(jsonObj_returnBody.get("zone").isJsonNull() ? ""
						: jsonObj_returnBody.get("zone").getAsString());

				mine.setAge(jsonObj_returnBody.get("age").isJsonNull() ? ""
						: jsonObj_returnBody.get("age").getAsString());

				// 给这个人创建数据库
				String dbName = "db_"
						+ MainApplication.getInstance().getMineUserInfo()
								.getUid() + ".db";
				MyDBHelper db = new MyDBHelper(dbName);
				db.getWritableDatabase();
				// 登陆进去
				Intent intent = new Intent();
				intent.setClass(this, MainActivity.class);
				startActivity(intent);
			}

			break;

		case 201:
			Toast.makeText(this, jsonObj_LoginReturn.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();
			break;
		case 202:
			Toast.makeText(this, jsonObj_LoginReturn.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();
			break;
		case 203:
			Toast.makeText(this, jsonObj_LoginReturn.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();
			break;
		default:
			Toast.makeText(this, "登陆失败", Toast.LENGTH_LONG).show();
			break;
		}

	}

	@Override
	public void XmppReceiveMessage(Message msg) {
		// TODO 自动生成的方法存根

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意
				intent.addCategory(Intent.CATEGORY_HOME);
				this.startActivity(intent);
				return true;
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void requestError() {
		// TODO 自动生成的方法存根

	}
}
